import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { NzNotificationService } from 'ng-zorro-antd';
import { SECRETKER } from 'src/app/bean/bean';
import { SEND_EMAIL_SUCCESS } from 'src/app/bean/responseStatus';
import { UtilMethod } from 'src/environments/environment';
import {Md5} from 'ts-md5';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
  validateForm!: FormGroup;
  md5EmailVerifyCode!: string;
  verifyEmail!: string;
  httpOptions = {
    headers: new HttpHeaders({
    'token' : 'aaaaa'
  })
  }

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
    return {};
  }

  telVlidators = (control: FormControl): { [s: string]: boolean } => {
    const phoneReg = new RegExp('/^(((\\d{3,4}-)?[0-9]{7,8})|(1(3|4|6|7|8|9)\\d{9}))$/');
    if (!phoneReg.test(control.value)) {
      return {error: true};
    }
    return {};
  }

  getCaptcha(e: MouseEvent): void {
    this.verifyEmail = this.validateForm.value.email;
    this.sendEmail();

  }

  async clickRegister(): Promise<void> {

    const tempMd5EmailVerifyCode = this.md5EmailVerifyCode;
    this.md5EmailVerifyCode = '';
    const md5 = Md5.hashStr(this.validateForm.value.captcha + SECRETKER);
    if (md5 !== tempMd5EmailVerifyCode || tempMd5EmailVerifyCode === '') {
      this._notification.create('error', '系统提醒', '验证码错误');
      return;
    }
    if (this.verifyEmail !== this.validateForm.value.email
        || this.validateForm.value.email === '') {
      this._notification.create('error', '系统提醒', '请重新获取验证码');
      return;
    }
    const data = await this.addUser();

  }

  addUser(): any {
    const userHeaders = {
      headers: new HttpHeaders({
      })
    };
    userHeaders.headers = userHeaders.headers.append('sign', this.createSign());
    const data = this.http.post(UtilMethod.MONITOR_DEV_API + '/user/addUser', this.validateForm.value, userHeaders).toPromise();
    this.router.navigate(['/login']);
    return data;
  }



  sendEmail(): void {
    const userHeaders = {
      headers: new HttpHeaders({
      })
    };
    userHeaders.headers = userHeaders.headers.append('sign', this.createSign());

    this.http.post(UtilMethod.MONITOR_DEV_API + '/user/sendEmail',
        {email: this.validateForm.value.email, nickname: this.validateForm.value.nickname}, userHeaders).subscribe(
      (hgs: any) => {
        if (hgs.errorCode === SEND_EMAIL_SUCCESS) {
          this._notification.create('success', '系统提醒', hgs.errorMsg);
        }  else {
          this._notification.create('error', '系统提醒', hgs.errorMsg);
        }
        this.md5EmailVerifyCode = hgs.data;
        console.log(' this.md5EmailVerifyCode=' +  this.md5EmailVerifyCode);
      });
  }


  createSign(): string{
    console.log('email = ' + this.validateForm.value.email);
    const sign = Md5.hashStr('email=' + this.validateForm.value.email
                                + '&nickname=' + this.validateForm.value.nickname
                                + '&secretKey=' + SECRETKER);
    console.log('createSign = ' + sign);

    return sign + '';
  }

  constructor(private fb: FormBuilder,
              private http: HttpClient,
              private router: Router, /** 路由 */
              private _notification: NzNotificationService, /** 提示 */) {}

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      email: [null, [Validators.email, Validators.required]],
      password: [null, [Validators.required]],
      checkPassword: [null, [Validators.required, this.confirmationValidator]],
      nickname: [null, [Validators.required]],
      phoneNumberPrefix: ['+86'],
      phoneNumber: [null, [Validators.required, this.telVlidators]],
      // website: [null, [Validators.required]],
      captcha: [null, [Validators.required]],
      agree: [false]
    });
  }
}

